class MpSwitch extends HTMLElement {
  static get observedAttributes() {
    return ["item", "text", "disabled", "checked"];
  }

  constructor() {
    super();
    this.attachShadow({ mode: "open" });
    this.isChecked = this.hasAttribute("checked");
  }

  connectedCallback() {
    this.render();
    this.attachEventListeners();
  }

  attributeChangedCallback(name, oldValue, newValue) {
    this.isChecked = this.hasAttribute("checked");
    this.render();
    this.attachEventListeners();
  }

  attachEventListeners() {
    const input = this.shadowRoot.querySelector("input");
    if (input) {
      input.addEventListener("change", () => {
        this.isChecked = input.checked;
        this.toggleAttribute("checked", this.isChecked);
        this.render();
      });
    }
  }

  render() {
    const item = this.getAttribute("item") || "";
    const text = this.getAttribute("text") || "";
    const disabled = this.hasAttribute("disabled");
    const switchClassName = this.isChecked ? "switch-true" : "switch-false";

    this.shadowRoot.innerHTML = `
        <style>
          @import url('./src/mp-design-tokens/components-styles/Switch.css');
        </style>
        <div class="switch ${switchClassName}">
          <label for="${item}">${text}</label>
          <div class="switch-bg">
            <input
              id="${item}"
              name="${item}"
              type="checkbox"
              ${disabled ? "disabled" : ""}
              ${this.isChecked ? "checked" : ""}
              class="switch-hidden"
            />
            <span class="switch-handle"></span>
          </div>
        </div>
      `;
  }
}

customElements.define("mp-switch", MpSwitch);
